package net.htjs.mobile.android.crm;


import java.security.MessageDigest;

import net.htjs.mobile.android.crm.db.CacheUrl;
import net.htjs.mobile.android.crm.db.DatabaseHandler;
import net.htjs.mobile.android.crm.util.FileService;
import net.htjs.mobile.android.crm.util.L;
import android.graphics.Bitmap;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MyWebClient extends WebViewClient {
	private DatabaseHandler dbh;
	public MyWebClient(DatabaseHandler dbh){
		this.dbh=dbh;
	}
	@Override
	public boolean shouldOverrideUrlLoading(WebView view, String url) {

		view.loadUrl(url);
		Log.d("webViewload", url);
		return true;
	}

	// 页面加载前调方法定义
	public void onPageStarted(WebView view, String url, Bitmap favicon) {

		super.onPageStarted(view, url, favicon);
	}

	public void onPageFinished(WebView view, String url) {
		Log.d("WebView", "onPageFinished ");
		view.loadUrl("javascript:window.local_obj.showSource('<head>'+"
				+ "document.getElementsByTagName('html')[0].innerHTML+'</head>');");
		super.onPageFinished(view, url);
	}
	public void onLoadResource(WebView view, String url) {
		Log.d("WebViewR", "LOADING    "+url);
		String md5=MD5(url);
		long time=System.currentTimeMillis();
		if(url.lastIndexOf(".")>0&&L.FT.get(url.substring(url.lastIndexOf(".")))!=null){
			if(L.CU.get(md5)==null){
				//CacheUrl cu=new CacheUrl(time,url,md5,time+"");
				//dbh.addCU(cu);
				//L.CU.put(md5, url);
				super.onLoadResource(view, url);
			}else{
				
				super.onLoadResource(view, url);
			}
		}else{
			
			super.onLoadResource(view, url);
		}
    }
	
	
	public final static String MD5(String s) {
		  char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
		  'a', 'b', 'c', 'd', 'e', 'f' };
		  try {
		   byte[] strTemp = s.getBytes();
		   //使用MD5创建MessageDigest对象
		   MessageDigest mdTemp = MessageDigest.getInstance("MD5");
		   mdTemp.update(strTemp);
		   byte[] md = mdTemp.digest();
		   int j = md.length;
		   char str[] = new char[j * 2];
		   int k = 0;
		   for (int i = 0; i < j; i++) {
		    byte b = md[i];
		    //System.out.println((int)b);
		    //将没个数(int)b进行双字节加密
		    str[k++] = hexDigits[b >> 4 & 0xf];
		    str[k++] = hexDigits[b & 0xf];
		   }
		   return new String(str);
		  } catch (Exception e) {return null;}
		} 
}

final class InJavaScriptLocalObj {
	public void showSource(String html) {
		Log.d("HTML", html);
	}
}